﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Image = System.Windows.Controls.Image;

namespace ThreadManagerTesterApp
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        private ImageDownloader imageDownloader;

        private DateTime starttime;

        public Window1()
        {
            InitializeComponent();

            Application.Current.Exit += (CurrentExit);
            

            

        }
        
        private void SetUpNewDownloader()
        {
            imageDownloader = new ImageDownloader();        
        
            imageDownloader.AddImageUrl(new Uri("http://nant.sourceforge.net/logo.gif"));
            imageDownloader.AddImageUrl(new Uri("http://fluentnhibernate.org/images/logo.png"));
            imageDownloader.AddImageUrl(new Uri("http://nhforge.org/cfs-file.ashx/__key/CommunityServer.Components.SiteFiles/logos/NHLogoSmall.gif"));
            imageDownloader.AddImageUrl(new Uri("http://nant.sourceforge.net/logo.gif"));
            imageDownloader.AddImageUrl(new Uri("http://fluentnhibernate.org/images/logo.png"));
            imageDownloader.AddImageUrl(new Uri("http://nhforge.org/cfs-file.ashx/__key/CommunityServer.Components.SiteFiles/logos/NHLogoSmall.gif"));
            imageDownloader.AddImageUrl(new Uri("http://nant.sourceforge.net/logo.gif"));
            imageDownloader.AddImageUrl(new Uri("http://fluentnhibernate.org/images/logo.png"));
            imageDownloader.AddImageUrl(new Uri("http://nhforge.org/cfs-file.ashx/__key/CommunityServer.Components.SiteFiles/logos/NHLogoSmall.gif"));
            imageDownloader.AddImageUrl(new Uri("http://nant.sourceforge.net/logo.gif"));
            imageDownloader.AddImageUrl(new Uri("http://fluentnhibernate.org/images/logo.png"));
            imageDownloader.AddImageUrl(new Uri("http://nhforge.org/cfs-file.ashx/__key/CommunityServer.Components.SiteFiles/logos/NHLogoSmall.gif"));
            imageDownloader.AddImageUrl(new Uri("http://nant.sourceforge.net/logo.gif"));
            imageDownloader.AddImageUrl(new Uri("http://fluentnhibernate.org/images/logo.png"));
            imageDownloader.AddImageUrl(new Uri("http://nhforge.org/cfs-file.ashx/__key/CommunityServer.Components.SiteFiles/logos/NHLogoSmall.gif"));
            imageDownloader.AddImageUrl(new Uri("http://nant.sourceforge.net/logo.gif"));
            imageDownloader.AddImageUrl(new Uri("http://fluentnhibernate.org/images/logo.png"));
            imageDownloader.AddImageUrl(new Uri("http://nhforge.org/cfs-file.ashx/__key/CommunityServer.Components.SiteFiles/logos/NHLogoSmall.gif"));
            imageDownloader.AddImageUrl(new Uri("http://nant.sourceforge.net/logo.gif"));
            imageDownloader.AddImageUrl(new Uri("http://fluentnhibernate.org/images/logo.png"));
            imageDownloader.AddImageUrl(new Uri("http://nhforge.org/cfs-file.ashx/__key/CommunityServer.Components.SiteFiles/logos/NHLogoSmall.gif"));
            imageDownloader.AddImageUrl(new Uri("http://nant.sourceforge.net/logo.gif"));
            imageDownloader.AddImageUrl(new Uri("http://fluentnhibernate.org/images/logo.png"));
            imageDownloader.AddImageUrl(new Uri("http://nhforge.org/cfs-file.ashx/__key/CommunityServer.Components.SiteFiles/logos/NHLogoSmall.gif"));
            imageDownloader.AddImageUrl(new Uri("http://nant.sourceforge.net/logo.gif"));
            imageDownloader.AddImageUrl(new Uri("http://fluentnhibernate.org/images/logo.png"));
            imageDownloader.AddImageUrl(new Uri("http://nhforge.org/cfs-file.ashx/__key/CommunityServer.Components.SiteFiles/logos/NHLogoSmall.gif"));

            imageDownloader.MaxNumberOfConcurentWorkers = 5;
            imageDownloader.ImageDownloadStarted += imageDownloader_ImageDownloadStarted;
            imageDownloader.ImageDownloaded += ImageDownloaded;
            imageDownloader.AllImagesDownloaded += AllImagesDownloaded;            
        }

        void imageDownloader_ImageDownloadStarted(object sender, DownloadImageState state)
        {
            if (Application.Current == null)
                return;

            Application.Current.Dispatcher.BeginInvoke(
                DispatcherPriority.Send, new Action(delegate
                {
                    this.goImages.IsEnabled = true;
                    this.lb.Items.Add(string.Format("Started download of {0}", state.Url));
                }));         
        }

        void AllImagesDownloaded(object sender)
        {
            if (Application.Current == null)
                return;

            Application.Current.Dispatcher.BeginInvoke(
                DispatcherPriority.Send, new Action(delegate
                {
                    this.goImages.IsEnabled = true;
                    this.lb.Items.Add("All Finished.");
                }));           
        }

        void ImageDownloaded(object sender, DownloadImageState state)
        {
            if (Application.Current == null)
                return;

            Application.Current.Dispatcher.BeginInvoke(
                DispatcherPriority.Send, new Action(delegate
                {
                    lb.Items.Add("Item Finished " + state.Url + (state.ThereWereErrors ? " With Error: " + state.LastErrorMessage : ""));
                    if (state.WasCanceled)
                    {
                        lb.Items.Add(" It was canceled");
                        return;
                    }
                    
                    if (!state.ThereWereErrors && state.DownloadedImage != null)
                    {
                        var bimage = new BitmapImage();
                        bimage.BeginInit();
                        var bytes = (byte[])new ImageConverter().ConvertTo(
                                                    state.DownloadedImage,
                                                    typeof(byte[]));

                        bimage.StreamSource = new MemoryStream(bytes);
                        bimage.EndInit();

                        var image = new Image {Source = bimage, Stretch = Stretch.None};

                        var panel = new StackPanel();
                        panel.Children.Add(new TextBlock() {Text = state.Url + ":"});
                        panel.Children.Add(image);

                        wrap.Items.Add(panel);
                    }
                }));                
            
        }

        void CurrentExit(object sender, ExitEventArgs e)
        {
            if (this.imageDownloader.IsWorking)
            {
                this.imageDownloader.Abort();
            }            
        }

        private void goImages_Click(object sender, RoutedEventArgs e)
        {
            if (imageDownloader != null && imageDownloader.IsWorking)
            {
                return;
            }
            
            this.SetUpNewDownloader();
            
            this.starttime = DateTime.Now;

            goImages.IsEnabled = false;
            lb.Items.Clear();
            wrap.Items.Clear();

            lb.Items.Add("Starting..." + DateTime.Now);

            imageDownloader.FetchAllImages();
        }

        private void AbortAll(object sender, RoutedEventArgs e)
        {
            this.imageDownloader.Abort();
        }

        private void Pause(object sender, RoutedEventArgs e)
        {
            if (!this.imageDownloader.IsPaused)
            {
                this.imageDownloader.Pause();
            }
            else
            {
                this.imageDownloader.Resume();
            }
        }
    }
}
